package com.xps.charmingshop;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;

import com.jude.utils.JUtils;
import com.squareup.leakcanary.LeakCanary;
import com.xps.charmingshop.utils.SharedPreferencesUtils;
import com.xps.charmingshop.view.activity.LoginActivity;

import java.lang.ref.SoftReference;
import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Flowable;


@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class App extends Application implements Application.ActivityLifecycleCallbacks {
    private static App INSTANCE;
    ArrayList<SoftReference<Activity>> activitiesCollected = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        //初始化本地字段存储
        SharedPreferencesUtils.init(this);
        JUtils.initialize(this);

        registerActivityLifecycleCallbacks(this);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    public void exitApp() {
        Flowable.just(activitiesCollected).flatMap(Flowable::fromIterable)
                .filter(softAct -> softAct.get() != null && (!softAct.get().isFinishing() || !softAct.get().isDestroyed()))
                .forEach(softAct -> softAct.get().finish());
        Intent intent3 = new Intent(this, LoginActivity.class);
        intent3.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent3.putExtra("zhanghao", "1");
        startActivity(intent3);
        SharedPreferencesUtils.putBoolean("isSave", "boolean", false);
        SharedPreferencesUtils.putString("name", "String", "");
        SharedPreferencesUtils.putString("password", "String", "");
    }

    public static App getInstance() {
        return INSTANCE;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        activitiesCollected.add(new SoftReference<Activity>(activity));
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
